package ai.leinao.notify.dingtalk.utils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;
import org.apache.commons.codec.binary.Base64;
import java.net.URLEncoder;

/**
 * 钉钉机器人签名工具类
 *
 * @author zhong.wang
 * @date 2025/7/15
 */
public class DingTalkRobotSignUtil {
    private static final Logger log = LoggerFactory.getLogger(DingTalkRobotSignUtil.class);

    /**
     * 获取签名
     * @param timestamp
     * @param secret
     * @return
     */
    public static String getSign(long timestamp, String secret) {
        String stringToSign = timestamp + "\n" + secret;
        try{
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
            String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)),"UTF-8");
            return sign;
        }catch (Exception e){
            log.error("getSign error:{}", e);
        }
        return null;
    }
}
